﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using HtmlAgilityPack;
using Torrenter.Common.Objects;
using System.Net;
using System.Xml.Linq;

namespace Torrenter.Manager.Services
{
    public class SearcherService
    {

        #region public methods



        public Torrent SearchTorrent(SingleEpTorrentSearch search)
        {
            try
            {
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            
            //open the search page uri (with results sorted by seeders number
            // pirate bay uri ->
            string searchString = GetSearchString(search.SearchString);

            Trace.WriteLine("searching for: " + search.SearchString);

            //search page html
          //  string s = GetHtml(searchString);
            //doc.Load(s);
            var hw = new HtmlWeb();
            doc = hw.Load(searchString);
            
            //doc.LoadHtml(s);
            var tt = doc.DocumentNode.Descendants("table").Where((e) => e.Attributes["id"].Value == "searchResult").FirstOrDefault();
            if (tt == null)
            {
                Trace.WriteLine("failed, no results: " + search.SearchString);
                return null;
            }
            var cl = tt.Descendants("div").Where((e) => e.Attributes["class"].Value == "detName");
            //iterate in the result until you find the right result
            foreach (var torrent in cl)
            {
                var torrentName = torrent.Element("a").InnerText;
                if (search.isMatch(torrentName))
                {
                    // create new
                    var elem = torrent.ParentNode.Elements("a").Where((e) => e.Attributes["title"].Value == "Download this torrent using magnet").First();

                    //the torrent uri
                    var torrentLink = elem.Attributes["href"].Value;
                    search.Torrent.DownloadLocation = torrentLink;
                    return search.Torrent;
                }    
            }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("failed, got exception "+ex.Message+" no matching results: " + search.SearchString);
            }
            
            Trace.WriteLine("failed, no matching results: " + search.SearchString);
            return null;
        }

        

        private IEnumerable<XElement> GetTorrentsFromPage(XElement sp)
        {
            //find the results table element
            var table =  sp.Descendants("table").Where((e) => e.Attribute("id").Value == "searchResult").First();
            return table.Descendants("div").Where((e) => e.Attribute("class").Value == "detName");
        }

        private string GetSearchString(string searchstring)
        {
            var eps = searchstring.Replace(" ", "%20");
            return string.Format("http://thepiratebay.se/search/{0}/0/7/0", eps);
        }

        private string GetHtml(string address)
        {
            
            
            WebClient wc = new WebClient();
            
            return wc.DownloadString(address);
            #region old
            //Stream dataStream = null;
            //StreamReader reader = null;
            //HttpWebResponse response = null;
            //try
            //{
            //    //WebClient wc = new WebClient();
            //    //return wc.DownloadString(address);
            //    // Create a request for the URL. 		
            //    WebRequest request = WebRequest.Create(address);
            //    // If required by the server, set the credentials.
            //    request.Credentials = CredentialCache.DefaultCredentials;
            //    // Get the response.
            //    response = (HttpWebResponse)request.GetResponse();
            //    // Display the status.
            //    //Console.WriteLine(response.StatusDescription);
            //    // Get the stream containing content returned by the server.
            //    dataStream = response.GetResponseStream();
            //    // Open the stream using a StreamReader for easy access.
            //    reader = new StreamReader(dataStream);
            //    // Read the content.
            //    return reader.ReadToEnd();
            //    // Display the content.
            //    //Console.WriteLine(responseFromServer);
            //}
            //catch (Exception ex)
            //{
            //    Debugger.Break();
            //}
            //finally
            //{
            //    reader.Close();
            //    dataStream.Close();
            //    response.Close();    
            //}
            //return string.Empty;
            //// Cleanup the streams and the response.



            #endregion // old
            
        }

        #region old code

        //public TorrentSearchResult SearchTorrent(SingleEpTorrentSearch search)
        //{
        //    //open the search page uri (with results sorted by seeders number
        //    // pirate bay uri ->
        //    string searchString = GetSearchString(search.SearchString);

        //    //search page html
        //    string s = GetHtml(searchString);
        //    XElement sp = XElement.Parse(s);
        //    //iterate in the result until you find the right result
        //    foreach (var torrent in GetTorrentsFromPage(sp))
        //    {
        //        var torrentName = torrent.Element("a").Value;
        //        if (search.isMatch(torrentName))
        //        {
        //            // create new
        //            var elem = torrent.Parent.Elements("a").Where((e) => e.Attribute("title").Value == "Download this torrent").First();

        //            //the torrent uri
        //            var torrentLink = elem.Attribute("herf").Value;

        //            //download the torrent
        //            Download(torrentLink);

        //        }
        //    }


        //    //goto result page, find torrent uri

        //    //download torrent?


        //    return new TorrentSearchResult();
        //}

        //public bool Download(Torrent torrent)
        //{
        //    WebClient wc = new WebClient();
        //    wc.DownloadFile(torrent.DownloadLocation,Path.Combine(DownloadLocation,torrent.Name));
        //    return true;
        //}

        //public bool Download(string uri)
        //{
        //    WebClient wc = new WebClient();
        //    //wc.DownloadFile(uri, DownloadLocation);            
        //    var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TorrentDownloadDirName);
        //    if (!Directory.Exists(dir))
        //    {
        //        Directory.CreateDirectory(dir);
        //    }
        //    var location = Path.Combine(dir, uri.Split('/').Last());
        //    wc.DownloadFile(uri, location);

        //    return true;
        //}

        #endregion // old download code

        
        #endregion // public methods
    }
}
